package org.cleverframe.core.fileupload.servlet;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;
import org.cleverframe.core.fileupload.attributes.FileuploadSessionAttributes;
import org.cleverframe.core.fileupload.vo.FileuploadProgress;

/**
 * 文件上传进度监听器实现类<br>
 * 
 * @author LiZW
 * @version 2015年9月2日 下午1:50:19
 */
public class LocalProgressListener implements ProgressListener
{
    /** 上传文件的客户端Session */
    private HttpSession session;
    
    public LocalProgressListener(HttpSession session)
    {
        this.session = session;
    }
    
    /* （非 Javadoc）
     * 更新上传文件的状态信息
     * pBytesRead : 已经上传到服务器的字节数
     * pContentLength : 所有文件的总大小
     * pItems : 表示第几个文件
     */
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems)
    {
        FileuploadProgress fileuploadProgress = (FileuploadProgress) session.getAttribute(FileuploadSessionAttributes.FILEUPLOAD_PROGRESS);
        if(fileuploadProgress == null)
        {
            fileuploadProgress = new FileuploadProgress();
            session.setAttribute(FileuploadSessionAttributes.FILEUPLOAD_PROGRESS, fileuploadProgress);
        }
        fileuploadProgress.setBytesRead(pBytesRead);
        fileuploadProgress.setContentLength(pContentLength);
        fileuploadProgress.setItemIndex(pItems);
        if(pBytesRead >= pContentLength)
        {
            fileuploadProgress.setComplete(true);
        }
        
        try
        {
            // TODO 文件上传休眠仅方便测试
            Thread.sleep(10);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    /*--------------------------------------------------------------
     *          getter、setter
     * -------------------------------------------------------------*/
    public HttpSession getSession()
    {
        return session;
    }

    public void setSession(HttpSession session)
    {
        this.session = session;
    }
}
